<?php
namespace app\admin\controller;
use app\admin\validate\PayCoinsValidate;
use app\service\PayCoinService;
use think\exception\ValidateException;
class PayCoins extends Admin
{
    public function __construct(PayCoinService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index()
    {
        if (!$this->request->isPost()) {
            $this->assign("title","充值提现币种配置");
            return $this->fetch("index");
        }
        $params = $this->request->post();
        $where =[];
        if (!empty($params["coin_name"])) {
            $where[] = ['coin_name', 'like', "%{$params['coin_name']}%"];
        }
        if (!empty($params["pay_status"])) {
            $where[] = ['pay_status', '=', $params["pay_status"]];
        }
        if (!empty($params["withdraw_status"])) {
            $where[] = ['withdraw_status', '=', $params["withdraw_status"]];
        }
        $ret = $this->service->getList($where);
        $this->result($ret);
    }

    private function save()
    {
        $params = $this->request->Post();
        $data =[
            "coin_name"=>$params["coin_name"],
            "icon"=>$params["icon"],
            "id"=>$params["id"] ?? 0,
            "sort"=>$params["sort"],
            "network"=>$params["network"],
            "address"=>$params["address"],
            "pay_status"=>$params["pay_status"],
            "pay_min_num"=>$params["pay_min_num"],
            "fee_type"=>$params["fee_type"],
            "fee"=>$params["fee"],
            "withdraw_min_num"=>$params["withdraw_min_num"],
            "withdraw_max_num"=>$params["withdraw_max_num"],
            "withdraw_status"=>$params["withdraw_status"],
        ];
        $action = $this->request->action();
        try {
            validate(PayCoinsValidate::class)->scene($action)->check($data);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $ret = $this->service->save($data);
        if ($ret) {
            $this->success("操作成功");
        } else {
            $this->error("保存失败");
        }
    }
    public function add()
    {
        if (!$this->request->isPost()) {
            $this->assign("title","添加充值提现币种配置");
            $this->assign("vo",null);
            return $this->fetch("form");
        }
        $this->save();
    }

    public function edit()
    {
        if (!$this->request->isPost()) {
            $this->assign("title","编辑充值提现币种配置");
            $id = $this->request->get("id");
            if (!$id) {
                throw new ValidateException("缺少id");
            }
            $vo = $this->service->get($id);
            if (empty($vo)) {
                throw new ValidateException("不存在对应的币种详情");
            }
            $this->assign("vo",$vo);
            return $this->fetch("form");
        }
        $this->save();
    }
}